package com.changyinBus.common.utils;

import javax.servlet.http.HttpServletRequest;

public class WebUtils {
    /**
     * 获取当前请求的完整域名（包含协议）
     */
    public static String getFullDomain(HttpServletRequest request) {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();

        StringBuilder url = new StringBuilder();
        url.append(scheme).append("://").append(serverName);

        if (serverPort != 80 && serverPort != 443) {
            url.append(":").append(serverPort);
        }

        if (contextPath != null && !contextPath.isEmpty()) {
            url.append(contextPath);
        }

        return url.toString();
    }

    /**
     * 获取基础域名（不包含上下文路径）
     */
    public static String getBaseDomain(HttpServletRequest request) {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();

        StringBuilder url = new StringBuilder();
        url.append(scheme).append("://").append(serverName);

        if (serverPort != 80 && serverPort != 443) {
            url.append(":").append(serverPort);
        }

        return url.toString();
    }

    /**
     * 判断是否为本地环境
     */
    public static boolean isLocalEnvironment(HttpServletRequest request) {
        String serverName = request.getServerName();
        return "localhost".equals(serverName) ||
                "127.0.0.1".equals(serverName) ||
                "0:0:0:0:0:0:0:1".equals(serverName);
    }
}
